package cn.whpu.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {
    //定义一个properties对象
    private static Properties props;
    //定义一个Map,用于存放我们创建的对象。我们把它称之为容器
    private static Map<String, Object> beans;

    //使用静态代码块
    static {
        try {
            //实例化
            props = new Properties();
            //获取properties对象的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            //实例化容器
            beans =new HashMap<String, Object>();
            Enumeration<Object> keys = props.keys();
            while (keys.hasMoreElements()){
                String key =keys.nextElement().toString();
                String beanPath =props.getProperty(key);
                //反射创建对象
                Object value =Class.forName(beanPath).newInstance();
                //把
                beans.put(key,value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据bean的名称获取对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }

//    /**
//     * 根据bean的名称获取对象
//     * @param beanName
//     * @return
//     */
//    public static Object getBean(String beanName) {
//        Object bean = null;
//        String beanPath = props.getProperty(beanName);
//        try {
//            bean = Class.forName(beanPath).newInstance();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        return bean;
//    }
}
